#include "./../../../include/online/WebPageQuery/RedisClient.h"
#include "./../../../include/online/Tools/MyLogger.h"
#include <memory>

RedisClient *RedisClient::_pInstance = nullptr;
pthread_once_t RedisClient::_once = PTHREAD_ONCE_INIT;

RedisClient *RedisClient::getInstance()
{
    pthread_once(&_once, init_r);
    return _pInstance;
}

// 根据key值进行查询
string RedisClient::get(const string &key)
{
    auto value = _redis->get(key);
    if (value)
    {
        return *value;
    }
    else
    {
        return "NotFound";
    }
}

// 往redis缓存中写入数据
void RedisClient::set(const string &key, const string &value)
{
    LogInfo("插入redis:" + key + "  " + value);
    _redis->set(key, value);
    return;
}

// 构造函数，允许自定义连接池大小
RedisClient::RedisClient(const std::string &host = "127.0.0.1", int port = 6379, size_t pool_size = 5)
: _host(host)
, _port(port)
, _pool_size(pool_size)
{
    // 设置连接选项
    ConnectionOptions connection_options;
    connection_options.host = _host;  // Redis 服务器地址
    connection_options.port = _port;  // Redis 服务器端口
    
    // 设置连接池选项
    ConnectionPoolOptions pool_options;
    pool_options.size = _pool_size; // 设置连接池大小

    // 创建 Redis 客户端
    _redis = std::make_unique<Redis>(connection_options, pool_options);
}

RedisClient::~RedisClient()
{
    
}

void RedisClient::init_r()
{
    if (_pInstance == nullptr)
    {
        _pInstance = new RedisClient("127.0.0.1", 6379, 10);
        atexit(destory);
    }
    return;
}

void RedisClient::destory()
{
    if (_pInstance)
    {
        delete _pInstance;
        _pInstance = nullptr;
    }
    return;
}
